<template>
  <div class="edit-box">
    <el-drawer v-model="dialogFormVisible" :title="dialogTitle" :close-on-click-modal="false" direction="rtl"
      @close="dialogClose">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules">
        <el-form-item style="width:100%;" label="岗位名称" prop="roleName">
          <el-input v-model="dialogForm.roleName" placeholder="请输入岗位名称" @keypress.enter="submitHandle" />
        </el-form-item>
        <el-form-item style="width:100%;" label="岗位描述" prop="roleDesc">
          <el-input v-model="dialogForm.roleDesc" placeholder="请输入岗位描述" type="textarea" @keypress.enter="submitHandle" />
        </el-form-item>
        <el-form-item style="width:100%;" label="权限选择" prop="menuIds">
          <el-tree ref="treeRef" :data="treeData" show-checkbox node-key="menuId" highlight-current :props="defaultProps"
            @check-change="treeChange" />
        </el-form-item>
        <el-form-item style="width:100%;" label="岗位状态" prop="state">
          <el-radio-group v-model="dialogForm.state">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="footer-box">
        <el-button style="margin-left:auto;" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitHandle">确定</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { nextTick, reactive, ref, toRefs } from 'vue'
import api from '../api'
import { warningDeal, successDeal } from '@/utils/utils'
import hexMD5 from "@/utils/md5.min.js"
export default {
  setup(props, context) {
    const dialogFormRef = ref(null)
    const treeRef = ref(null)

    const menuIdsPass = (rule, value, callback) => {
      if (!state.dialogForm.menuIds || state.dialogForm.menuIds.length == 0) {
        callback(new Error('请选择岗位权限'))
      } else {
        callback()
      }
    }

    const state = reactive({
      dialogTitle: '创建岗位',
      dialogFormVisible: false,
      dialogType: 'add',
      showPass: false,
      dialogForm: {
        state: 1,
      },
      treeData: [],
      roleOptions: [],
      dialogFormRules: {
        roleName: [
          { required: true, message: '请输入岗位名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入岗位描述', trigger: 'blur' },
        ],
        menuIds: [
          { required: true, validator: menuIdsPass, trigger: 'blur' },
        ],
        state: [
          { required: true, message: '请选择岗位状态', trigger: 'blur' },
        ],
      },
      defaultProps: {
        label: 'name',
        children: 'children',
      },
    })

    function dialogShow(type, data = null) {
      state.dialogType = type
      state.dialogTitle = (type == 'add') ? '新增岗位' : (type == 'edit') ? '编辑岗位' : ''
      if (data) {
        getDetails(data.roleId)
      }
      getMenu()
      state.dialogFormVisible = true
    }

    function getDetails(roleId) {
      const obj = {
        roleId,
      }
      api.roleDetail(obj).then(res => {
        if (res.code == '200') {
          state.dialogForm = res.data
          setClickBox(state.dialogForm.menus)
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function submitHandle() {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          if (state.dialogType == 'add') {
            api.addRole(state.dialogForm).then(res => {
              if (res.code == '200') {
                successDeal(res.msg)
                context.emit('dialogClose', true)
                state.dialogFormVisible = false
              } else {
                warningDeal(res.msg)
              }
            }).catch(err => {
              console.log(err)
            })
          } else if (state.dialogType == 'edit') {
            api.modifyRole(state.dialogForm).then(res => {
              if (res.code == '200') {
                successDeal(res.msg)
                context.emit('dialogClose', true)
                state.dialogFormVisible = false
              } else {
                warningDeal(res.msg)
              }
            }).catch(err => {
              console.log(err)
            })
          }
        }
      })
    }

    function dialogClose() {
      setClickBox([])
      dialogFormRef.value.resetFields()
    }

    function getMenu() {
      api.roleMenu().then(res => {
        if (res.code == '200') {
          state.treeData = res.data.list
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function treeChange() {
      let myArr = treeRef.value.getCheckedNodes()
      const menuIdList = []
      myArr.map(item => {
        if (item.parentId) {
          menuIdList.push(item.parentId)
        }
        menuIdList.push(item.menuId)
      })
      state.dialogForm.menuIds = menuIdList
    }

    //回显树
    function setClickBox(data) {
      const chooseList = []
      let arrLength = 0
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length > 0) {
          data[i].children.forEach(item => {
            chooseList.push(item.menuId)
            arrLength++
          })
        } else {
          chooseList.push(data[i].menuId)
          arrLength++
        }
      }
      nextTick(() => {
        treeRef.value.setCheckedKeys(chooseList)
        treeChange()
      })
    }

    return {
      ...toRefs(state),
      treeRef,
      dialogFormRef,
      dialogShow,
      dialogClose,
      submitHandle,
      treeChange,
    }
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
  padding: 20px 20px 60px 20px !important;
}
:deep(.el-tree) {
  .el-tree-node {
    box-sizing: border-box;
    padding: 5px 0;
    font-size: 12px;
  }
}
.footer-box {
  position: fixed;
  bottom: 20px;
  right: 20px;
}
</style>